import axios from "axios";
import Vue from "vue";

const http = axios.create({
  baseURL: process.env.VUE_APP_API_URL || "/api/web"
});
http.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    if (localStorage.token) {
      config.headers.Authorization = "Bearer " + localStorage.token;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);
http.interceptors.response.use(res => {
  console.log(res.data.error_num);
  if (res.data.error_num === 1) {
    // alert(res.data.msg)
    Vue.prototype.$toast({
      text: res.data.msg,
      type: "danger",
      duration: 3000
    });
  }

  if (res.data.status === false) {
    if (res.data.error.indexOf("token") != -1) {
      localStorage.clear();
      setTimeout(()=>{
        location.reload()
      },1000)
    }
    Vue.prototype.$toast({
      text: '登录信息过期，请重新登录',
      type: "danger",
      duration: 3000
    });
  }
  return res;
});
export default http;
